package com.zhx.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Date;

/**
 * @author zhanghaixuan
 * @version 1.0
 * date 2021/5/20-10:20 上午
 * description netty客户端
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        /**
         * 对应IOClent里面起的发送线程
         */
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap
                //指定线程模型
                .group(group)
                //指定IO类型为NIO  基本都是NIO
                .channel(NioSocketChannel.class)
                //处理逻辑
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                });
        //连接信息
        Channel channel = bootstrap.connect("127.0.0.1", 8000)
                .addListener(future -> {
                    if (future.isSuccess()) {
                        System.out.printf("连接成功");
                    }else{
                        System.out.printf("连接失败");
                    }

                })
                .channel();

        while (true) {
            channel.writeAndFlush(new Date() + ": hello world!");
            Thread.sleep(2000);
        }
    }
}
